//
//  ChangeIPController.m
//  PeaPodAgent
//
//  Created by MasterLing on 2017/8/17.
//  Copyright © 2017年 MasterLing. All rights reserved.
//

#import "AppChangeIPController.h"
#import "UIBarButtonItem+Extension.h"
#import "KKPositionedButton.h"
#import <NetworkExtension/NetworkExtension.h>
#import "VpnConnector.h"
#import "VpnInfo.h"
//#import "LYTNetDiagnoser.h"
#import "IpListController.h"
#import "UIButton+MCore.h"
#import <UIView+TYAlertView.h>
#import "ChangeButton.h"





//豌豆动画
#define dWidth 14
#define dSpace 23
#define ddeltaY 20
#define changeIP @"192.168.50.1"






@interface AppChangeIPController ()<VpnConnectorDelegate>

@property (weak, nonatomic) IBOutlet UIButton *areaWithIpButton;

@property (weak, nonatomic) IBOutlet UIButton *changeIpButton;

@property (weak, nonatomic) IBOutlet UIButton *disconnectButton;

@property (weak, nonatomic) IBOutlet UIButton *oneChangIpButton;


@property (weak, nonatomic) IBOutlet UIImageView *neiceyuanImageView;

@property (weak, nonatomic) IBOutlet UIImageView *zhongjianyuanImageView;

@property (weak, nonatomic) IBOutlet UIImageView *waiceyuanImageView;


@property (weak, nonatomic) IBOutlet UIView *superView;

@property (weak, nonatomic) IBOutlet KKPositionedButton *selectLine;

@property (weak, nonatomic) CALayer* layer;

@property (nonatomic, strong) VpnConnector *connector;

@property (nonatomic, strong) VpnInfo *vpnInfo;

@property (nonatomic, assign) VPNStatus vpnStatus;

@end

@implementation AppChangeIPController

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self baseUILoad];
    
    _connector = [VpnConnector vpnConnector];
    _connector.delegate = (id)self;
    
    [_connector loadProviderManage:^(VPNStatus vpnStatus) {
        [self vpnStatusDidChange:vpnStatus];
    }];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userSelectLine:) name:KKCitySelectNotification object:nil];
    
}


- (void)userSelectLine:(NSNotification *)notification{
    [self connectvpnAction:nil];
}

- (VpnInfo *)vpnInfo{
    if (!_vpnInfo) {
        _vpnInfo = [[VpnInfo alloc] init];
        _vpnInfo.serverAddress = @"118.25.77.157";
        _vpnInfo.password = @"1234567";
        _vpnInfo.username = @"admin@qq.com";
        _vpnInfo.remoteID = @"118.25.77.157";
        _vpnInfo.sharedSecret = @"1234567";
        _vpnInfo.preferenceTitle = @"豌豆云";
    }
    return _vpnInfo;
}

- (void) baseUILoad{
    self.navigationItem.title = @"豌豆代理";
//    [self.selectLine sizeToFit];
//    self.connectChangeIp.uxy_acceptEventInterval = 3.0;
    self.selectLine.buttonPositioned = KKPositionedButtonTypeTitleLeft;
    
    [self.disconnectButton addRoundedCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft withRadii:CGSizeMake(20, 20)];
}

#pragma mark  设置ip和ip归属地
- (void) setIpWithArea {
    NSString *server_name = [[NSUserDefaults standardUserDefaults] objectForKey:@"server_name"];
    if (server_name.length > 4) {
        [self.areaWithIpButton setTitle:server_name forState:UIControlStateNormal];
    }
}


#pragma mark  列表选择
- (IBAction)selectLineAction:(UIButton *)sender {
    IpListController *ipListC = [[IpListController alloc] init];
    [self.navigationController pushViewController:ipListC animated:YES];
}


#pragma mark  开始连接事件
- (IBAction)connectvpnAction:(UIButton *)sender {
    NSString *fisrtkey = [[NSUserDefaults standardUserDefaults] objectForKey:@"fisrtkey"];
    if (fisrtkey.length < 6) {
        UIAlertController *controller=[UIAlertController alertControllerWithTitle:@"Whether to allow network permissions" message:@"Do not access any of your data after opening network permissions,Will not collect your information" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *act1=[UIAlertAction actionWithTitle:@"don't allow" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self vpnManagerConnection];
        }];
        UIAlertAction *act2=[UIAlertAction actionWithTitle:@"allow" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self vpnManagerConnection];
            [[NSUserDefaults standardUserDefaults] setObject:@"firstvalue" forKey:@"fisrtkey"];
        }];
        [controller addAction:act1];
        [controller addAction:act2];
        [self presentViewController:controller animated:YES completion:^{
            
        }];
    }else{
        [self vpnManagerConnection];
    }
}



- (void) vpnManagerConnection {
    if (self.vpnInfo.serverAddress.length<1) {
        [SVProgressHUD showInfoWithStatus:@"配置信息不完整"];
        return;
    }
    [self.connector checkVPNPreferenceSuccess:^(BOOL isInstalled) {
        if (isInstalled) {
            //判断是否连接上
            VPNStatus status = [self.connector getCurrentStatus];
            if (status == VPNStatusConnecting || status == VPNStatusConnected) {
                [self.connector stopVPNConnectSuccess:^{
                    
                }];
            }else{
                //开始之前刷新之前的信息
                [self.connector modifyVPNPreferenceWithData:self.vpnInfo success:^{
                    [self.connector startVPNConnectSuccess:^{
                        
                    }];
                }];
            }
        }else{
            
            [self.connector createVPNPreferenceWithData:self.vpnInfo success:^{
                [self.connector startVPNConnectSuccess:^{
                    
                }];
            }];
        }
    }];
}

#pragma mark  连接动画
- (void) connectingAnimation{
    [self.superView.layer addSublayer:self.layer];
    self.neiceyuanImageView.image = [UIImage imageNamed:@"douzibeijing"];
    
    [self scaleAnimation];
}
#pragma mark  断开连接动画
- (void) disconnectingAnimation{
    
}
#pragma mark  断开状态UI
- (void) disconnectedStatus{
    [self.waiceyuanImageView.layer removeAllAnimations];
    
    [self.zhongjianyuanImageView.layer removeAllAnimations];
    
    [self.layer removeFromSuperlayer];
    
    self.neiceyuanImageView.image = [UIImage imageNamed:@"neicengyuan_1"];
    
    //断开状态
    self.oneChangIpButton.hidden = NO;
    self.disconnectButton.hidden = YES;
    self.changeIpButton.hidden = YES;
}
#pragma mark  连接状态UI
- (void) connectedStatus{
    //连接上的状态
    [self.waiceyuanImageView.layer removeAllAnimations];
    
    [self.zhongjianyuanImageView.layer removeAllAnimations];
    
    [self.layer removeFromSuperlayer];
    
    self.neiceyuanImageView.image = [UIImage imageNamed:@"neicengyuan_2"];
    
    self.oneChangIpButton.hidden = YES;
    self.disconnectButton.hidden = NO;
    self.changeIpButton.hidden = NO;
    
    [self setIpWithArea];
}
#pragma mark  更改ip事件
- (IBAction)changeipAction:(UIButton *)sender {
    [self vpnManagerConnection];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self vpnManagerConnection];
    });
}


#pragma mark  断开连接事件
- (IBAction)stopConnectAction:(UIButton *)sender {
    [self vpnManagerConnection];
}


- (void) scaleAnimation{
    
    [self.waiceyuanImageView.layer addAnimation:[self createBasicAnimationWithKeyPath:@"transform.scale" toValue:0.9] forKey:nil];
    
    [self.zhongjianyuanImageView.layer addAnimation:[self createBasicAnimationWithKeyPath:@"transform.scale" toValue:0.92] forKey:nil];
    
}

- (CALayer *)layer{
    if (!_layer) {
        CGFloat middelX = self.superView.bounds.size.width/2.0;
        CGFloat middelY = self.superView.bounds.size.height/2.0;
        CALayer* layer = [CALayer new];
        UIColor* tintColor = [UIColor whiteColor];
        CGFloat duration = 1.0f;
        NSArray *beginTimes = @[@0.07f, @0.14f, @0.21f];
        CAMediaTimingFunction *timingFunciton = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        
        // Animation
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
        
        animation.duration = duration;
        animation.keyTimes = @[@0.0f, @0.33f, @0.66f, @1.0f];
        animation.values = @[@0.0f, @(ddeltaY), @(-ddeltaY), @0.0f];
        animation.timingFunctions = @[timingFunciton, timingFunciton, timingFunciton];
        animation.repeatCount = HUGE_VALF;
        animation.removedOnCompletion = NO;
        
        
        CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
        
        animation1.duration = duration;
        animation1.keyTimes = @[@0.0f, @0.33f, @0.66f, @1.0f];
        animation1.values = @[@0.0f, @(-ddeltaY), @(ddeltaY), @0.0f];
        animation1.timingFunctions = @[timingFunciton, timingFunciton, timingFunciton];
        animation1.repeatCount = HUGE_VALF;
        animation1.removedOnCompletion = NO;
        
        
        CAShapeLayer *circle0 = [CAShapeLayer layer];
        UIBezierPath *circlePath0 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, dWidth, dWidth) cornerRadius:dWidth / 2];
        
        animation.beginTime = [beginTimes[0] floatValue];
        circle0.fillColor = tintColor.CGColor;
        circle0.path = circlePath0.CGPath;
        [circle0 addAnimation:animation forKey:@"animation"];
        circle0.frame = CGRectMake(middelX-dWidth/2.0-dSpace-dWidth, middelY-dWidth/2.0, dWidth, dWidth);
        [layer addSublayer:circle0];
        
        
        
        CAShapeLayer *circle1 = [CAShapeLayer layer];
        UIBezierPath *circlePath1 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, dWidth, dWidth) cornerRadius:dWidth / 2];
        
        animation1.beginTime = [beginTimes[1] floatValue];
        circle1.fillColor = tintColor.CGColor;
        circle1.path = circlePath1.CGPath;
        [circle1 addAnimation:animation1 forKey:@"animation"];
        circle1.frame = CGRectMake(middelX-dWidth/2.0, middelY-dWidth/2.0, dWidth, dWidth);
        [layer addSublayer:circle1];
        
        
        CAShapeLayer *circle2 = [CAShapeLayer layer];
        UIBezierPath *circlePath2 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, dWidth, dWidth) cornerRadius:dWidth / 2];
        
        animation.beginTime = [beginTimes[2] floatValue];
        circle2.fillColor = tintColor.CGColor;
        circle2.path = circlePath2.CGPath;
        [circle2 addAnimation:animation forKey:@"animation"];
        circle2.frame = CGRectMake(middelX+dWidth/2.0+dSpace, middelY-dWidth/2.0, dWidth, dWidth);
        [layer addSublayer:circle2];
        _layer = layer;
    }
    return _layer;
}

//创建缩放动画
- (CABasicAnimation *)createBasicAnimationWithKeyPath:(NSString *)keyPath toValue:(CGFloat)toValue{
    //创建动画对象
    CABasicAnimation *scaleAni = [CABasicAnimation animation];
    
    //设置动画属性
    scaleAni.keyPath = keyPath;
    
    //设置动画的起始位置。也就是动画从哪里到哪里。不指定起点，默认就从positoin开始
    scaleAni.toValue = @(toValue);
    
    //动画持续时间
    scaleAni.duration = 0.8;
    
    //动画重复次数
    scaleAni.repeatCount = CGFLOAT_MAX;
    
    return scaleAni;
}


//抽取创建Layer的公共方法
- (CALayer *)createLayerWithPosition:(CGPoint)position backgroundColor:(UIColor *)backgroundColor{
    //创建calayer
    CALayer *layer = [CALayer layer];
    //设置位置和大小
    
    layer.position = position;
    layer.bounds = CGRectMake(0, 0, 100, 100);
    
    
    //设置背景颜色
    layer.backgroundColor = [backgroundColor CGColor];
    
    //把layer添加到UIView的layer上
    [self.view.layer addSublayer:layer];
    
    return layer;
}

//创建基础Animation
- (CABasicAnimation *)createAnimation{
    //创建动画对象
    CABasicAnimation *scaleAni = [CABasicAnimation animation];
    //设置动画属性
    scaleAni.keyPath = @"transform.scale";
    
    //设置动画的起始位置。也就是动画从哪里到哪里。不指定起点，默认就从positoin开始
    
    scaleAni.toValue = @(0.5);
    
    //动画持续时间
    scaleAni.duration = 1.0;
    
    //动画的节奏
    scaleAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    //动画持续重复次数
    scaleAni.repeatCount = CGFLOAT_MAX;
    
    
    return scaleAni;
}


- (void)vpnConnectionDidRecieveError:(VpnConnectorError)error{
    switch (error) {
        case VpnConnectorErrorNone:
            break;
        case VpnConnectorErrorLoadPrefrence:
            break;
        case VpnConnectorErrorSavePrefrence:
            break;
        case VpnConnectorErrorRemovePrefrence:
            break;
        case VpnConnectorErrorStartVPNConnect:
            break;
        default:
            break;
    }
}

- (void)vpnStatusDidChange:(VPNStatus)status{
    switch (status) {
        case VPNStatusInvalid:
            break;
        case VPNStatusConnected:
        {
            self.vpnStatus = VPNStatusConnected;
            
            [[NSUserDefaults standardUserDefaults] setInteger:VPNStatusConnected forKey:KKVPNStatus];
            
            [self connectedStatus];
        }
            break;
        case VPNStatusDisconnected:
        {
            self.vpnStatus = VPNStatusDisconnected;
            
            [[NSUserDefaults standardUserDefaults] setInteger:VPNStatusConnected forKey:KKVPNStatus];
            
            [self disconnectedStatus];
        }
            break;
        case VPNStatusConnecting:
        {
            self.vpnStatus = VPNStatusConnecting;
            //连接中状态
            [[NSUserDefaults standardUserDefaults] setInteger:VPNStatusConnecting forKey:KKVPNStatus];
            
            [self connectingAnimation];
        }
            break;
        case VPNStatusDisconnecting:
        {
            self.vpnStatus = VPNStatusDisconnecting;
            //断开连接中状态
            [[NSUserDefaults standardUserDefaults] setInteger:VPNStatusDisconnecting forKey:KKVPNStatus];
            
            [self disconnectingAnimation];
        }
            break;
        default:
            break;
    }
}

@end
